package zheezes.protocol.impl.gd;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import zheezes.protocol.impl.gd.bean.MeterData;
import zheezes.protocol.impl.gd.converter.DateConverter;
import zheezes.util.ByteUtil;


public class Ctrl92Frame extends GdFrame {
	private byte total;
	private short fmseq;
	private byte cfseq;
	private short option;
	private Calendar cal = Calendar.getInstance();
	private List<MeterData> list = new ArrayList<MeterData>();
	private short lmseq;

	public Ctrl92Frame() {
		ctrl = (byte) 0x92;
	}
	
	public int sizeOfData() {
		int size = 9;
		if(list.size() > 0) {
			size += list.get(0).size();
		}
		return size;
	}

	@Override
	public int getData(byte[] buf, int offset) {
		int idx = offset;
		buf[idx++] = total;
		ByteUtil.stoc(buf, idx, fmseq);
		idx += 2;
		buf[idx++] = cfseq;
		ByteUtil.stoc(buf, idx, option);
		idx += 2;
		DateConverter.vtob(buf, idx, cal);
		idx += 3;
		byte[] tmp = null;
		for (MeterData mdb : list) {
			tmp = mdb.getBytes();
			System.arraycopy(tmp, 0, buf, idx, tmp.length);
			idx += tmp.length;
		}
		System.arraycopy(ByteUtil.stoc(lmseq), 0, buf, 0, 2);
		idx += 2;

		return idx - offset;
	}

	@Override
	public int setData(byte[] buf, int offset, int max) {
		int idx = offset;
		total = buf[idx++];
		fmseq = ByteUtil.ctos(buf, idx);
		idx += 2;
		cfseq = buf[idx++];
		option = ByteUtil.ctos(buf, idx);
		idx += 2;
		byte[] tmp = new byte[3];
		System.arraycopy(buf, idx, tmp, 0, 3);
		cal.setTime(DateConverter.btov(tmp).getTime());
		idx += 3;
		while (idx < max - 2) { // there is tow bytes for last meter sequence
			MeterData mdb = new MeterData();
			idx += mdb.setBytes(buf, idx, max);
			list.add(mdb);
		}
		lmseq = ByteUtil.ctos(buf, idx);
		idx += 2;

		return idx - offset;
	}
	
	public MeterData[] getMetersData() {
		return list.toArray(new MeterData[0]);
	}

	public byte getTotal() {
		return total;
	}

	public short getFmseq() {
		return fmseq;
	}

	public byte getCfseq() {
		return cfseq;
	}

	public short getOption() {
		return option;
	}

	public Calendar getCal() {
		return cal;
	}

	public short getLmseq() {
		return lmseq;
	}

	public void setTotal(byte total) {
		this.total = total;
	}

	public void setFmseq(short fmseq) {
		this.fmseq = fmseq;
	}

	public void setCfseq(byte cfseq) {
		this.cfseq = cfseq;
	}

	public void setOption(short option) {
		this.option = option;
	}

	public void setCal(Calendar cal) {
		this.cal = cal;
	}

	public void setLmseq(short lmseq) {
		this.lmseq = lmseq;
	}
}
